'
' Will Strohl (will.strohl@gmail.com)
' http://www.willstrohl.com
'
'Copyright (c) 2012, Will Strohl
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are 
'permitted provided that the following conditions are met:
'
'Redistributions of source code must retain the above copyright notice, this list of 
'conditions and the following disclaimer.
'
'Redistributions in binary form must reproduce the above copyright notice, this list 
'of conditions and the following disclaimer in the documentation and/or other 
'materials provided with the distribution.
'
'Neither the name of Will Strohl, Simple Redirect, nor the names of its contributors may be 
'used to endorse or promote products derived from this software without specific prior 
'written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
'TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
'BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
'ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
'DAMAGE.
'

Imports DotNetNuke.UI.Skins.Controls
Imports DotNetNuke
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Entities.Modules
Imports WillStrohl.Modules.SimpleRedirect.RedirectController

Namespace WillStrohl.Modules.SimpleRedirect

    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' The EditSimpleRedirect class is used to manage content
    ''' </summary>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Partial Class Details
        Inherits SimpleRedirectModuleBase

#Region " Private Members "

        Private p_RedirectId As Integer = Null.NullInteger
        Private p_Enabled As Nullable(Of Boolean)
        Private p_EditRedirectsUrl As String = String.Empty

#End Region

#Region " Private Properties "

        Private ReadOnly Property RedirectId() As Integer
            Get
                Return p_RedirectId
            End Get
        End Property

        Private ReadOnly Property Enabled As Boolean
            Get
                If Not p_Enabled.HasValue Then
                    If Not Settings(SETTING_ENABLE) Is Nothing Then
                        p_Enabled = Boolean.Parse(Settings(SETTING_ENABLE).ToString())
                    Else
                        p_Enabled = True
                    End If
                Else
                    p_Enabled = True
                End If

                Return p_Enabled
            End Get
        End Property

        Protected ReadOnly Property EditRedirectsUrl() As String
            Get
                If String.IsNullOrEmpty(p_EditRedirectsUrl) Then
                    p_EditRedirectsUrl = EditUrl(String.Empty, String.Empty, "Edit")
                End If

                Return p_EditRedirectsUrl
            End Get
        End Property

#End Region

#Region " Event Handlers "

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Page_Load runs when the control is loaded
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try
                If Not Page.IsPostBack Then
                    BindData()
                End If
            Catch exc As Exception    'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        Private Sub lnkEnable_Click(sender As Object, e As System.EventArgs) Handles lnkEnable.Click
            EnableTracking()
            SendBackToModule()
        End Sub

        Private Sub lnkClose_Click(sender As Object, e As System.EventArgs) Handles lnkClose.Click
            SendBackToModule()
        End Sub
        
        Private Sub lnkClearHistory_Click(sender As Object, e As System.EventArgs) Handles lnkClearHistory.Click
            ClearHistory()
            SendBackToList()
        End Sub

#End Region

#Region " Helper Methods "

        Private Sub BindData()

            LocalizeModule()

            lnkClearHistory.Visible = UserInfo.IsSuperUser

            If Not Request.Params(PARAM_REDIRECTID) Is Nothing Then
                p_RedirectId = Integer.Parse(Request.Params(PARAM_REDIRECTID).ToString(), Globalization.NumberStyles.Integer)
            End If

            Dim blnEnabled As Boolean = Null.NullBoolean
            If Not Settings(SETTING_ENABLE) Is Nothing Then
                blnEnabled = Boolean.Parse(Settings(SETTING_ENABLE).ToString())
            End If

            Dim blnTracking As Boolean = Null.NullBoolean
            If Not Settings(SETTING_TRACKING) Is Nothing Then
                blnTracking = Boolean.Parse(Settings(SETTING_TRACKING).ToString())
            End If

            pnlNoDetails.Visible = Not blnEnabled

            If Not blnTracking Then
                UI.Skins.Skin.AddModuleMessage(Me, GetLocalizedString("NoDetails.Text"), ModuleMessage.ModuleMessageType.YellowWarning)
            End If

            If RedirectId > 0 Then

                Dim ctlModule As New RedirectController

                txtRedirect.Text = ctlModule.GetRedirect(RedirectId).RedirectTo
                txtHits.Text = ctlModule.GetRedirectVisitCount(RedirectId)

                rptDomain.DataSource = ctlModule.GetDomainsByRedirect(RedirectId)
                rptDomain.DataBind()

                rptUrls.DataSource = ctlModule.GetUrlsByRedirect(RedirectId)
                rptUrls.DataBind()

            End If

        End Sub

        Private Sub LocalizeModule()

            lnkEnable.Text = GetLocalizedString("lnkEnable.Text")
            lnkClose.Text = GetLocalizedString("lnkClose.Text")
            lnkClearHistory.Text = GetLocalizedString("lnkClearHistory.Text")

        End Sub

        Private Sub EnableTracking()

            Dim ctlModule As New ModuleController
            ctlModule.UpdateTabModuleSetting(TabModuleId, SETTING_TRACKING, True)
            ModuleController.SynchronizeModule(ModuleId)

        End Sub

        Private Sub ClearHistory()

            Dim ctlModule As New RedirectController
            ctlModule.DeleteVisitorsByRedirect(RedirectId)

        End Sub

        Private Sub SendBackToModule()
            Response.Redirect(NavigateURL())
        End Sub

        Private Sub SendBackToList()

            Dim strEditUrl As String = EditUrl(String.Empty, String.Empty, "Edit")
            Response.Redirect(strEditUrl)

        End Sub

        Protected Function ReformatUrlForLink(ByVal Url As Object) As String
            If Not Url Is Nothing Then
                Return String.Format("<a href=""{0}"" target=""_blank"">{0}</a>", Url.ToString())
            Else
                Return String.Empty
            End If
        End Function

        Protected Function ReformatDomainForLink(ByVal Domain As Object) As String
            If Not Domain Is Nothing Then
                Return String.Format("<a href=""http://{0}"" target=""_blank"">{0}</a>", Domain.ToString())
            Else
                Return String.Empty
            End If
        End Function

#End Region

    End Class

End Namespace